package com.tim.file.utils;

import com.utils.VerifyUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.UUID;

/**
 * @author tim
 * @version 1.0
 * @date 2022/6/13 15:10
 */
@Slf4j
public class FileUtils {
    /**
     * 本地目录生成文件路径
     *
     * @param fileBasePath
     * @return
     */
    public static String getAllFilePath(String fileBasePath, String lesseeCode) {
        String baseFilePath = fileBasePath + File.separator + getAbsFilePathName(lesseeCode);
        File file = new File(baseFilePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        return baseFilePath;
    }

    /**
     * 本地目录生成文件路径
     *
     * @param fileBasePath
     * @return
     */
    public static String getAllFileAndAbs(String fileBasePath, String absPath) {
        String baseFilePath = fileBasePath + File.separator + absPath;
        File file = new File(baseFilePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        return baseFilePath;
    }

    public static String getAbsFilePathName(String lesseeCode) {
        String yyyyMMdd = VerifyUtil.getDate("yyyyMMdd");
        String baseFilePath = lesseeCode + File.separator + yyyyMMdd;
        return baseFilePath;
    }

    /**
     * 获取文件id规则名称
     * 如果是临时文件标记临时文件特征
     *
     * @param isTemp
     * @return
     */
    public static String getFileIdName(String isTemp) {
        String id = UUID.randomUUID().toString().replaceAll("-", "");
        if ("1".equals(isTemp)) {
            id = "tem_" + id;
        } else {
            id = "per_" + id;
        }
        return id;
    }


    /**
     * java获取文件的md5值
     *
     * @param fis 输入流
     * @return
     */
    public static String md5HashCode(InputStream fis) {
        try {
            //拿到一个MD5转换器,如果想使用SHA-1或SHA-256，则传入SHA-1,SHA-256
            MessageDigest md = MessageDigest.getInstance("MD5");

            //分多次将一个文件读入，对于大型文件而言，比较推荐这种方式，占用内存比较少。
            byte[] buffer = new byte[1024];
            int length = -1;
            while ((length = fis.read(buffer, 0, 1024)) != -1) {
                md.update(buffer, 0, length);
            }
            fis.close();
            //转换并返回包含16个元素字节数组,返回数值范围为-128到127
            byte[] md5Bytes = md.digest();
            BigInteger bigInt = new BigInteger(1, md5Bytes);//1代表绝对值
            return bigInt.toString(16);//转换为16进制
        } catch (Exception e) {
            e.printStackTrace();
            log.error("============文件加密hash报错===========");
            return "";
        }
    }

    /**
     * 文件输出
     *
     * @param response
     * @param in
     * @param fileName
     * @param contentType
     * @throws IOException
     */
    public static void fileOutputStream(HttpServletResponse response, FileInputStream in, String fileName,
                                        String contentType, String fileLength) throws IOException {
        OutputStream output;
        output = response.getOutputStream();
        response.reset();
        String downFileName = new String(fileName.getBytes("gb2312"), "ISO8859-1");
        response.setHeader("Content-Disposition", "attachment;filename=" + downFileName);
        response.addHeader("Content-Length", "" + fileLength);
        response.setContentType(contentType);
        int len = 0;
        byte[] buffer = new byte[1024];
        while ((len = in.read(buffer)) > 0) {
            output.write(buffer);
        }
        output.flush();
        output.close();
        in.close();
    }
}
